package 线程与并发;

/**
 * 两个线程交替执行任务
 */
public class TwoThread {
    public static void main(String[] args) {
        Runnable r1 = () -> System.out.println("线程1 do something");
        Runnable r2 = () -> System.out.println("线程2 do something");
        Alternate alternate = new Alternate(r1, r2);
        alternate.start();
    }

    static class Alternate extends Thread {
        private volatile boolean flag;
        private String lock = "";
        private Runnable runnable1;
        private Runnable runnable2;

        Alternate(Runnable runnable1, Runnable runnable2) {
            this.runnable1 = runnable1;
            this.runnable2 = runnable2;
        }

        @Override
        public void run() {
            new Thread(() -> {
                while (true) {
                    synchronized (lock) {
                        try {
                            if (flag) {
                                lock.wait();
                            }
                            runnable1.run();
                            flag = true;
                            lock.notify();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
            new Thread(() -> {
                while (true) {
                    synchronized (lock) {
                        try {
                            if (!flag) {
                                lock.wait();
                            }
                            runnable2.run();
                            flag = false;
                            lock.notify();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }
}
